package com.kefu.chat.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kefu.chat.mapper.ChatChannelMapper;
import com.kefu.chat.mapper.ChatFaqMapper;
import com.kefu.chat.model.ChatChannel;
import com.kefu.chat.model.ChatFaq;
import com.kefu.chat.vo.ChatFaqSearchVo;
import com.kefu.common.service.AbstractKefuService;
import com.kefu.common.util.Assert;
import com.kefu.common.util.JacksonUtil;
import icu.mhb.mybatisplus.plugln.core.JoinLambdaWrapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;

@Service
public class ChatFaqService extends AbstractKefuService<ChatFaq> {
    @Resource
    private ChatFaqMapper chatFaqMapper;
    @Resource
    private ChatChannelMapper chatChannelMapper;
    @Override
    public ChatFaq getById(Serializable id) {
        ChatFaq info = super.getById(id);
        return info;
    }

    @Override
    public void deleteById(String id) {
        List<ChatChannel> chatChannels = chatChannelMapper.selectList(
                Wrappers.lambdaQuery(ChatChannel.class).eq(ChatChannel::getFaqId, id));
        Assert.isNotEmpty(chatChannels, "方案被使用，不能删除！");
        ChatFaq chatFaq = chatFaqMapper.selectByPrimaryKey(id);
        Assert.isNull(chatFaq, "已删除！");
        chatFaqMapper.deleteById(id);
        logger.info("删除常见问题信息:{}", JacksonUtil.toString(chatFaq));
        super.deleteById(id);
    }

    public Page<ChatFaq> listFaq(ChatFaqSearchVo search) {
        Page<ChatFaq> page = searchLambdaPage(search);
        return page;
    }

    public void batchDelete(List<String> ids) {
        Assert.isTrue(CollUtil.isEmpty(ids), "请选择要删除的快捷方案！");
        boolean flag = true;
        for (String id :
                ids) {
            Long count = chatChannelMapper.selectCount(Wrappers.lambdaQuery(ChatChannel.class).eq(ChatChannel::getFaqId, id));
            if (count > 0) {
                flag = false;
            }
        }
        Assert.isTrue(!flag, "快捷方案已经被绑定，不能删除!");
        chatFaqMapper.deleteBatchIds(ids);
    }
}
